package com.tjetc.service.impl;

import com.tjetc.common.JsonResult;
import com.tjetc.common.vo.user.SpotWithTagsView;
import com.tjetc.dao.*;
import com.tjetc.entity.*;
import com.tjetc.service.SpotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpotServiceImpl implements SpotService {
    @Autowired
    SpotMapper spotMapper;
    @Autowired
    CityMapper cityMapper;
    @Autowired
    TagsMapper tagsMapper;
    @Autowired
    LikesMapper likesMapper;

    @Override
    public JsonResult getAll() {
        List<Spot> spots = spotMapper.selectAll();
        return JsonResult.success("查询成功", spots);
    }

    @Override
    public JsonResult getTop(Long l) {
        List<Spot> spots = spotMapper.selectTop(l);
        return JsonResult.success("查询成功", spots);
    }

    @Override
    public JsonResult getBytagclazz() {
        List<Tag> activeTags = tagsMapper.getActiveTags("active");

        Map<String, List<Tag>> groupedTags = activeTags.stream()
                .collect(Collectors.groupingBy(Tag::getClazz));

        List<Spot> spots = spotMapper.selectAll();
        List<SpotWithTagsView> result = groupedTags.entrySet().stream()
                .map(entry -> {
                    String clazzName = entry.getKey();
                    List<Tag> tags = entry.getValue();
                    String image = tags.get(0).getImage();
                    String decription = tags.get(0).getDescription();
                    Long clazzId = tags.get(0).getClazzId();
                    List<Spot> filteredSpots = spots.stream()
                            .filter(spot -> {
                                boolean matches = spot.getTags().stream()
                                        .anyMatch(tagId -> {
                                            boolean tagMatches = tags.stream()
                                                    .anyMatch(tag -> {
                                                        boolean match = tag.getTagId().equals(tagId.getTagId());
                                                        return match;
                                                    });
                                            return tagMatches;
                                        });
                                return matches;
                            })
                            .collect(Collectors.toList());

                    SpotWithTagsView spotWithTagsView = new SpotWithTagsView();
                    spotWithTagsView.setClazzName(clazzName);
                    spotWithTagsView.setSpots(filteredSpots);
                    spotWithTagsView.setDescription(decription);
                    spotWithTagsView.setImage(image);
                    spotWithTagsView.setClazzId(clazzId);

                    return spotWithTagsView;
                })
                .collect(Collectors.toList());

        return JsonResult.success("查询成功", result);
    }

    @Override
    public JsonResult getSpotByCity(Long cityCode) {
        List<Spot> spots = spotMapper.selectByCity(cityCode);
        return JsonResult.success("查询成功", spots);
    }

    @Override
    public JsonResult findSpotById(Long id) {
        Spot spot =spotMapper.findSpotById(id);
        return JsonResult.success("查找景点成功",spot);
    }

    @Override
    public JsonResult getTopSpotsByCity(Long cityCode, int limit) {
        List<Spot> topSpots = spotMapper.selectTopSpotsByCityAndDimension(cityCode, "热度", limit);
        if (topSpots != null && !topSpots.isEmpty()) {
            return JsonResult.success("查询成功", topSpots);
        } else {
            return JsonResult.success("该城市暂无景点数据", null);
        }
    }

    @Override
    public JsonResult getTopByVisitorsCount(int limit) {
        List<Spot> spots = spotMapper.selectTopByVisitorsCount(limit);
        return JsonResult.success("查询成功", spots);
    }

    @Override
    public JsonResult getTopSpotsByCityAndVisitorsCount(Long cityCode, int limit) {
        List<Spot> spots = spotMapper.selectTopSpotsByCityAndVisitorsCount(cityCode, limit);
        if (spots != null && !spots.isEmpty()) {
            return JsonResult.success("查询成功", spots);
        } else {
            return JsonResult.success("该城市暂无景点访问量数据", null);
        }
    }

    @Override
    public JsonResult incrementSpotVisitorsCount(Long spotId) {
        int result = spotMapper.incrementVisitorsCount(spotId);
        if (result > 0) {
            return JsonResult.success("更新访问量成功");
        } else {
            return JsonResult.fail("更新访问量失败");
        }
    }

    @Override
    public JsonResult getSpotDetail(Long spotId) {
        // 先增加访问量
        spotMapper.incrementVisitorsCount(spotId);
        // 再查询景点详情
        Spot spot = spotMapper.selectSpotById(spotId);
        if (spot != null) {
            return JsonResult.success("查询成功", spot);
        } else {
            return JsonResult.fail("景点不存在");
        }
    }

    @Override
    public JsonResult getSpotsByCityWithFilters(Long cityCode, Integer page, Integer pageSize, String type, String priceRange, Integer rating, String sortKey, String sortDirection) {
        int offset = (page - 1) * pageSize;
        List<Spot> spots = spotMapper.selectSpotsByCityWithFilters(cityCode, type, priceRange, rating, sortKey, sortDirection, offset, pageSize);
        int total = spotMapper.countSpotsByCityWithFilters(cityCode, type, priceRange, rating);
        List<String> types = spotMapper.getSpotTypesByCity(cityCode);

        List<Map<String, Object>> spotList = new ArrayList<>();
        for (Spot spot : spots) {
            Map<String, Object> spotMap = new HashMap<>();
            spotMap.put("spotId", spot.getSpotId());
            spotMap.put("spotName", spot.getSpotName());
            spotMap.put("type", spot.getTags().isEmpty() ? null : spot.getTags().get(0).getTagName());
            spotMap.put("averageCost", spot.getAverageCost());
            spotMap.put("openingHours", spot.getOpenTime());
            spotMap.put("visitDuration", spot.getVisitDuration());
            spotMap.put("score", spot.getScore());
            spotMap.put("description", spot.getDescription());
            spotMap.put("coverImage", spot.getCoverImage());
            spotList.add(spotMap);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("total", total);
        result.put("currentPage", page);
        result.put("pageSize", pageSize);
        result.put("types", types);
        result.put("spots", spotList);

        return JsonResult.success("查询成功", result);
    }


}
